package com.manager.execute.controller;

import com.manager.common.ssh.RemoteExecuteLinuxCommandTools;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.utils.ResultVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/execute")
public class ExecuteSSHController {

    @Value("${linux.ssh.ip}")
    private String ip;

    @Value("${linux.ssh.port}")
    private Integer port;

    @Value("${linux.ssh.password}")
    private String password;

    @Value("${linux.ssh.user.name}")
    private String userName;

    @RequestMapping("/ssh")
    public ResultVO executeSSH(@RequestBody String command) {
        try{
            List<String> commands = ObjectUtils.jsonArray2Bean(command, String.class);
            if(commands == null || commands.isEmpty()){
                return ResultVO.success();
            }
            List<String> out = new ArrayList<>();
            boolean hasSuccess = RemoteExecuteLinuxCommandTools.excuteRemoteSSH(ip,userName,password,port,out,commands.toArray(new String[commands.size()]));
            if(!hasSuccess){
                return ResultVO.failed(out);
            }
            return ResultVO.success(out);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }
}
